import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { UserService } from "src/user/user.service";

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly userService: UserService
  ) {}

  async validateUser(username: string, pass: string): Promise<any> {
    const user = await this.userService.validateUser(username, pass);
    if (user) {
      // 从 user 对象中移除密码字段
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  async login(user: any) {
    const payload = {
      username: user.username,
      sub: user.userId
    };

    return {
      access_token: this.jwtService.sign(payload)
    };
  }
}
